package com.wang.auth.listener;

import com.wang.auth.service.SysLoginLogService;
import com.wang.model.system.SysLoginLog;
import com.wang.security.custom.CustomUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * @author wjh
 * @create 2023-06-14
 */
@Slf4j
@Component
public class AuthenticationSuccessListener implements ApplicationListener<AuthenticationSuccessEvent> {
    @Autowired
    private SysLoginLogService loginLogService;

    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        //用户通过输入用户名和密码登录成功
        // 登录账号
        CustomUser customUser = (CustomUser) event.getAuthentication().getPrincipal();
        SysLoginLog loginLog = new SysLoginLog();
        loginLog.setUsername(customUser.getSysUser().getUsername());
        loginLog.setIpaddr("127.0.0.1");
        loginLog.setMsg("登录成功");
        loginLog.setAccessTime(LocalDateTime.now().atOffset(ZoneOffset.UTC).toLocalDateTime());
        loginLog.setStatus(true);
        loginLogService.save(loginLog);
    }
}
